/**
 * service
 * @author ydr.me
 * @create 2019-09-29 19:13:38
 * @update 2019-09-29 19:13:38
 */

'use strict';
import axios from 'axios';
// import qs from 'blear.utils.querystring';
import { Message } from '@isyscore/base-ui';
import Vue from 'vue';
const load = function () {
    return Vue.prototype.$loading({
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0)'
    });
};
const stringify = (message) => {
    return typeof message === 'object' ? message.message : String(message);
};
const service = axios.create();
service.interceptors.request.use(
    (config) => {
        const isGetMethod = config.method.toUpperCase() === 'GET';
        load();
        if (!isGetMethod) {
            const data = config.data || {};
            const isFormData = data instanceof FormData;

            if (!isFormData) {
                config.headers['content-type'] = 'application/json';
                config.data = JSON.stringify(data);
            }
        }

        config.paramsSerializer = (params) => {
            // return qs.stringify(params);
            return '';
        };

        return config;
    },
    (err) => {
        throw err;
    }
);

service.interceptors.response.use(
    (res) => {
        const { code, message } = res.data;
        load().close();
        if (code && message) {
            throw new Error(message);
        }

        return res;
    },
    (err) => {
        load().close();
        const message = (err.response && err.response.data) || '网络出现了问题';
        console.log(message);
        Message.error(stringify(message));
        throw new Error(JSON.stringify(message));
    }
);

Vue.prototype.$service = service;
